import axios from 'axios';
import * as XLSX from 'xlsx';
import UserService from './UserService.js';
import { ElMessage } from 'element-plus';
import router from '../router';

// 创建axios实例
const api = axios.create({
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    },
    validateStatus: status => status >= 200 && status < 300
});

// 请求拦截器，自动加token
api.interceptors.request.use(config => {
    const token = localStorage.getItem('token') || (UserService.getCurrentUser && UserService.getCurrentUser().token) || '';
    if (token) {
        config.headers.token = token;
    }
    return config;
});

// 响应拦截器
api.interceptors.response.use(
    (response) => {

        return response
    },
    (error) => {
        //如果响应的状态码为401, 则路由到登录页面
        console.log('响应错误:', error);
        if (error.response.status === 401) {
            ElMessage.error('登录失效, 请重新登录')
            router.push('/login')
        } else {
            ElMessage.success('接口访问异常')
        }
        return Promise.reject(error)
    }
);


class DepartmentService {
    // 分页查询部门
    async getDepartmentListWithPage(params = {}) {
        try {
            const queryParams = { ...params };
            queryParams.currentUserId = UserService.getCurrentUserId();
            const response = await api.get('/api/department/list', { params: queryParams });
            return response.data;
        } catch (error) {
            console.error('获取分页部门列表失败:', error);
            throw error;
        }
    }

    // 查询单个部门详情
    async getDepartmentDetail(id) {
        try {
            const response = await api.get(`/api/department/${id}`);
            return response.data;
        } catch (error) {
            console.error('获取部门详情失败:', error);
            throw error;
        }
    }

    // 新增部门
    async addDepartment(data) {
        try {
            const currentUserId = UserService.getCurrentUserId();
            const response = await api.post('/api/department/add', data, {
                params: { currentUserId }
            });
            return response.data;
        } catch (error) {
            console.error('新增部门失败:', error);
            throw error;
        }
    }

    // 更新部门
    async updateDepartment(id, data) {
        try {
            const response = await api.put(`/api/department/${id}`, data);
            return response.data;
        } catch (error) {
            console.error('更新部门失败:', error);
            throw error;
        }
    }

    // 删除部门
    async deleteDepartment(id) {
        try {
            const response = await api.delete(`/api/department/${id}`);
            return response.data;
        } catch (error) {
            console.error('删除部门失败:', error);
            throw error;
        }
    }

};

export default new DepartmentService();